package com.bwie.gateway.filters;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.exceptions.BizExceptions;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import com.bwie.gateway.config.IgnoreWhitesConfig;
import com.bwie.gateway.utils.GatewayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @className: AuthFiles
 * @Description: TODO
 * @version: v1.８.0
 * @author: 汪菲阳
 * @date: 2025/8/24 11:29
 */
@Component
public class AuthFiles implements Ordered, GlobalFilter {
    @Autowired
    private IgnoreWhitesConfig ignoreWhitesConfig;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取所有的白名单
        List<String> whites = ignoreWhitesConfig.getWhites();
        //获取所有的请求路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //比较请求路径是否符合白名单
        if(StringUtils.matches(path,whites)){
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst(TokenConstants.TOKEN);
        //非空
        if (StringUtils.isEmpty(token)){
            return GatewayUtils.errorResponse(exchange,"token不能为空");
        }
        //合法
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            return GatewayUtils.errorResponse(exchange,"toke不合法");
        }
        //有效
        String userKey = JwtUtils.getUserKey(token);
        if (!redisTemplate.hasKey(TokenConstants.LOGIN_TOKEN_KEY+userKey)){
            return GatewayUtils.errorResponse(exchange,"请重新登录，token已失效");
        }
        //续期
        redisTemplate.expire(TokenConstants.LOGIN_TOKEN_KEY+userKey,30, TimeUnit.MINUTES);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
